package org.example.design.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
public class myController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //测试String
    @GetMapping("/testString")
    @ResponseBody
    public String testString() {
        redisTemplate.opsForValue().set("key", "value");
        String value = redisTemplate.opsForValue().get("key");
        System.out.println(value);
        redisTemplate.delete("key");
        return "OK";
    }

    //测试List
    @GetMapping("/testList")
    @ResponseBody
    public String testList() {
        redisTemplate.opsForList().leftPush("key", "a");
        redisTemplate.opsForList().leftPushAll("key", "b", "c", "d");
        List<String> values = redisTemplate.opsForList().range("key", 1, 2);
        System.out.println(values);
        redisTemplate.delete("key");
        return "OK";
    }

    ////测试HashMap
    @GetMapping("/testHashmap")
    @ResponseBody
    public String testHashmap() {
        redisTemplate.opsForHash().put("key", "name", "zhangsan");
        String value = (String) redisTemplate.opsForHash().get("key", "name");
        System.out.println(value);
        redisTemplate.opsForHash().delete("key", "name");
        boolean ok = redisTemplate.opsForHash().hasKey("key", "name");
        System.out.println(ok);
        redisTemplate.delete("key");
        return "OK";
    }

    //测试Set
    @GetMapping("/testSet")
    @ResponseBody
    public String testSet() {
        redisTemplate.opsForSet().add("key", "aaa", "bbb", "ccc");
        boolean ok = redisTemplate.opsForSet().isMember("key", "aaa");
        System.out.println(ok);
        redisTemplate.opsForSet().remove("key", "aaa");
        long n = redisTemplate.opsForSet().size("key");
        System.out.println(n);
        redisTemplate.delete("key");
        return "OK";
    }

    //测试Zset
    @GetMapping("/testZSet")
    @ResponseBody
    public String testZSet() {
        redisTemplate.opsForZSet().add("key", "吕布", 100);
        redisTemplate.opsForZSet().add("key", "赵云", 98);
        redisTemplate.opsForZSet().add("key", "典⻙", 95);
        Set<String> values = redisTemplate.opsForZSet().range("key", 0, 2);
        System.out.println(values);
        long n = redisTemplate.opsForZSet().count("key", 95, 100);
        System.out.println(n);
        redisTemplate.delete("key");
        return "OK";
    }
}
